from django.shortcuts import render, reverse, redirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from apps.crm import forms
from apps.crm.models import User
# Create your views here.


def base(request,template_name):
    return render(request, template_name)

def index(request):
    return render(request, 'index.html')

def logout(request):
    auth.logout(request)
    return redirect(reverse('login'))
# def index2(request):
#     return render(request, 'index.html')

def test(request):
    return render(request, 'test.html')

def job_count(request):
    return render(request, 'job_count.html')

def test_celery(request):
    from apps.count.tasks import checking_in_statistics
    result = checking_in_statistics.delay()
    # # print(dir(result))
    # from djcelery.models import PeriodicTask, IntervalSchedule
    # cron_n = 11
    # cron_type = 'seconds'
    # interval = IntervalSchedule.objects.get_or_create(every=cron_n, period=cron_type)[0]
    # task = PeriodicTask.objects.get_or_create(name='add100')[0]
    # task.interval = interval
    # task.args = [1, 1]
    # task.task = 'apps.crm.tasks.add'
    # task.save()
    return HttpResponse('OK')

from django.db import transaction
# 单独开启事物 atomic
@transaction.atomic()
def test_transaction(request):
    import datetime
    import time
    from apps.crm.models import CheckingIn
    sid = transaction.savepoint()
    # now0 = datetime.datetime.now()
    # today0 = datetime.date.today()
    # time0 = now0.strftime('%X')
    # CheckingIn.objects.create(date=today0, sign_time=time0, user=request.user)
    # time.sleep(1)
    # sid1 = transaction.savepoint()
    # now0 = datetime.datetime.now()
    # today0 = datetime.date.today()
    # time0 = now0.strftime('%X')
    #
    # # raise KeyError
    # try:
    #     CheckingIn.objects.create(date=today0, sign_time=time0, user=request.user)
    #     # raise KeyError
    #
    #     transaction.get_rollback()
    #     # 提交
    #     transaction.savepoint_commit(sid1)
    # except Exception as ex:
    #     # 回滚
    #     transaction.savepoint_rollback(sid1)
    with transaction.atomic:
        now0 = datetime.datetime.now()
        today0 = datetime.date.today()
        time0 = now0.strftime('%X')
        CheckingIn.objects.create(date=today0, sign_time=time0, user=request.user)
        transaction.set_rollback(True)
    # if transaction.get_rollback():
    #     transaction.savepoint_rollback(sid)
    # else:
    #     # 提交
    #     transaction.savepoint_commit(sid)

    return HttpResponse('test_transaction')

# def check_info(request):
#     return render(request, 'teacher/check_info.html')

# def course_record(request):
#     return render(request, 'comm/course_record.html')

def login(request):
    if request.method == 'GET':
        form = forms.LoginForm()
        kwgs = {
            'form': form
        }
        return render(request, 'login.html',kwgs)
    else:
        form = forms.LoginForm(request.POST)
        if form.is_valid():
            print('data OK')
            email = request.POST.get('email', '')
            password = request.POST.get('password','')
            user = auth.authenticate(email=email,password=password)
            if user is not None:
                auth.login(request, user)
                return redirect(reverse('index'))
            else:
                return render(request, 'login.html', {'form':form, 'error':'密码输入错误'})
        else:
            return render(request, 'login.html', {'form':form})

from django.core.mail import send_mail
def register(request):
    if request.method == 'GET':
        form = forms.DjangoForm()
        kwgs = {
            'form': form
        }
        return render(request, 'register.html',kwgs)
    else:
        form = forms.DjangoForm(request.POST)
        if form.is_valid():
            print('data OK')
            email = request.POST.get('email', '')
            username = request.POST.get('username','')
            password = request.POST.get('password','')
            password2 = request.POST.get('password2', '')
            if password == password2:
                print(email, username, password)
                User.objects.create_user(email=email, username=username, password=password)
                send_mail('主题send_mail', '注册成功', '287241081@qq.com',
                     ['{}'.format(email)], fail_silently=False)
                return render(request, 'login.html', {'form': form})

            else:
                print("两次密码不一致")
                return render(request, 'register.html', {'form': form, 'error': '两次密码不一致'})

def test_session(request):
    request.session['myname'] = 'hu'
    return HttpResponse(request.session)



